<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Vote;
use App\Models\VoteCls;
use App\Models\VoteOptions;
use App\Models\VoteTags;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Table;
use Illuminate\Support\Env;
use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;

class VoteController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        return Grid::make(new Vote(),function(Grid $grid) {

            // 禁止
            $grid->toolsWithOutline(false);

            $grid->setActionClass(Grid\Displayers\Actions::class);

            $grid->disableRowSelector();

            $grid->disableBatchDelete();

            // 设置初始排序条件
            $grid->model()->orderBy('sort_id','desc');

            $grid->model()->orderBy('id','desc');

            $grid->model()->orderBy('updated_at','desc');

            $grid->setActionClass(Grid\Displayers\Actions::class);

            $grid->column('sort_id')->editable(true)->sortable();

            // 关联 产品分类 表数据
            $grid->model()->with(['vote_cls']);

            $grid->column('vote_cls.title','分类');

            $grid->column('title')->textarea();

            $grid->column('title1','所属配置')->display('所属配置')->modal('所属配置',function($modal) {

                $modal->icon('feather icon-eye');

                // 获取分页数据，每页显示10条记录
                $options = VoteOptions::where('vote_id',$this->vote_id)->where('is_using',Env::get('APP_CONTENT_STATE'))->get()->map(function($comment) {
                    return $comment->only(['title','introduction','created_at']);
                });

                // 构建表格组件并返回
                return new Table(['标题','简介','发布时间'],$options);
            });

            $grid->column('time_on')->display(function($value) {
                return date('Y-m-d h:i',strtotime($value));
            })->sortable();

            $grid->column('time_off')->display(function($value) {
                return date('Y-m-d h:i',strtotime($value));
            })->sortable();

            $grid->column('thumbnail')->display(function($pictures) {

                if(empty($pictures)) {
                    $pictures = admin_url() . '/../themes/not.jpg';
                }
                else {

                    $pictures = admin_url() . '/../../../storage/app/public' . $pictures;
                }

                return $pictures;

            })->image();

            $grid->column('is_using')->switch('',true);

            $grid->column('created_at')->display(function($value) {
                return date('Y-m-d h:i',strtotime($value));
            })->sortable();

            $grid->column('updated_at')->display(function($value) {
                return date('Y-m-d h:i',strtotime($value));
            })->sortable();

            $grid->actions(function(Grid\Displayers\Actions $actions) {

                // append一个操作
                $actions->append('<br/><a href="' . admin_url('vote-options/create/') . '" title="配置选项">添加选项</a>');

                $actions->append('<br/><a href="' . request()->url() . '/../../../vote/' . $this->vote_id . '" title="' . $this->title . '" target="_blank">前端页面</a>');
            });

            $grid->filter(function(Grid\Filter $filter) {
                $filter->equal('title');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id,new Vote(),function(Show $show) {
            $show->field('c_key');
            $show->field('t_key');
            $show->field('user_id');
            $show->field('title');
            $show->field('time_on');
            $show->field('time_off');
            $show->field('sort_id');
            $show->field('vote_rule')->unescape();
            $show->field('prize');
            $show->field('keywords');
            $show->field('address');
            $show->field('telephone');
            $show->field('sponsor');
            $show->field('wx_qr_uri');
            $show->field('qr_code');
            $show->field('accumulate_votes');
            $show->field('player_num');
            $show->field('content')->unescape();
            $show->field('introduction');
            $show->field('images')->image();
            $show->field('thumbnail')->image();
            $show->field('is_using')->using([1 => '启用',0 => '禁用']);
            $show->field('is_comments')->using([1 => '启用',0 => '禁用']);
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {

        return Form::make(new Vote(),function(Form $form) {

            $form->disableResetButton();

            $form->disableEditingCheck();

            $form->disableViewCheck();

            $form->hidden('vote_id');

            $form->hidden('user_id');

            $form->hidden('slug');

            $form->tab('*基本信息*',function(Form $form) {

                $form->select('c_key')->placeholder('请选择分类！')
                    ->options(VoteCls::all()->pluck('title','c_key'))
                    ->required()
                    ->rules('min:1');

                $form->multipleSelect('t_key')->placeholder('请选择标签！')
                    ->options(VoteTags::all()->pluck('name','t_key'))
                    ->saving(function($value) {
                        // 转化成json字符串保存到数据库
                        return json_encode($value);
                    });

                $form->text('title')->required()->autofocus()->rules('required|min:1|max:85|regex:/^[^@!$%]/',[
                    'regex' => '标题存在非法字符！',
                ]);;

                $form->editor('vote_rule')->height(800)->required()->rules('min:1');

                $form->editor('prize')->required('min:1');

                $form->editor('content')->height(800)->required()->rules('min:1');

            })->tab('投票参数',function(Form $form) {

                $form->number('sort_id');

                $form->number('grade')->default(5);

                $form->text('keywords')->help('请用逗号把相应的关键词分开！');

                $form->text('address');

                $form->mobile('telephone');

                $form->text('sponsor');

                $form->number('accumulate_votes');

                $form->number('player_num');

                $form->textarea('introduction');

                $form->datetime('time_on')->default(now())->required('min:1');

                $form->datetime('time_off')->default(now())->required('min:1');

                $form->radio('is_using')->options([1 => '开启',0 => '禁用'])->default(1)->required('min:1');

                $form->radio('is_comments')->options([1 => '开启',0 => '禁用'])->default(1)->required('min:1');

            })->tab('图片上传',function(Form $form) {

                // 缩略图
                $form->image('thumbnail')
                    ->uniqueName()
                    ->autoUpload()
                    ->disk('public')
                    ->move('/images/vote')
                    ->maxSize(getConf('IMAGE_UPLOAD_SIZE'))
                    ->accept(getConf('IMAGE_UPLOAD_TYPE'))
                    ->override();

                // 图集
                $form->multipleImage('images')
                    ->uniqueName()
                    ->autoUpload()
                    ->disk('public')
                    ->move('/images/vote')
                    ->maxSize(getConf('IMAGE_UPLOAD_SIZE'))
                    ->accept(getConf('IMAGE_UPLOAD_TYPE'))
                    ->limit(3)
                    ->help('最多可以上传3张图片！')
                    ->override()
                    ->saveAsJson();

            });

            // 保存时
            $form->saving(function(Form $form) {

                if(empty($this->vote_id)) {
                    $form->vote_id = Str::uuid();
                }

                $form->user_id = Admin::user()->id;

                // 为空
                if(empty($form->slug)) {
                    $form->slug = Pinyin::permalink($form->title);
                }

            });

        });
    }
}
